package DataStructure.arrayRelevant.matrix;

import Common.Utils.UTFactory;
import org.junit.Test;

/**
 * @author 蔚蔚樱
 * @version 1.0
 * @date 2018-7-19 下午03:07:41
 * @author—Email micromicrohard@outlook.com
 * @description 矩阵置零
 * @blogURL https://leetcode-cn.com/problems/set-matrix-zeroes/submissions/
 * 给定一个 m x n 的矩阵，如果一个元素为 0 ，则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。
 */

public class Matrix_SetZero {

    @Test // 验证功能：从数据库获取测试数据，用于单元测试
    public void TestFunc() throws Exception {
        UTFactory.FullTest(this.getClass());
    }

    @Test // 调试功能 : 用于复现错误的测试案例
    public void DoubleTrack() throws Exception {
        String input = "{" +
                "{1,1,1,1,1}," +
                "{1,1,0,1,1}," +
                "{1,1,1,1,0}," +
                "{1,1,1,1,1}," +
                "}";
        String output = "{" +
                "{1,1,0,1,0}," +
                "{0,0,0,0,0}," +
                "{0,0,0,0,0}," +
                "{1,1,0,1,0}" +
                "}";
        UTFactory.DebugTest(this.getClass(), input, output);
    }

    public int[][] setMethod(int[][] matrix) {
        if (matrix == null || matrix.length == 0) {
            return matrix;
        }
        boolean columnZeroFlag = false; // 先扫列为0
        for (int[] ints : matrix) {
            if (ints[0] == 0) {
                columnZeroFlag = true;
                break;
            }
        }
        for (int[] row : matrix) {
            for (int i = 1; i < row.length; i++) { // attention : 列从 1 开始遍历
                if (row[i] == 0) {
                    matrix[0][i] = 0; // 列标记为0
                    row[0] = 0;       // 行标记为0
                }
            }
        }
        // 执行刷新 : 列刷新
        for (int i = 1; i < matrix[0].length; i++) {
            if (matrix[0][i] != 0) {
                continue;
            }
            for (int j = 1; j < matrix.length; j++) {
                matrix[j][i] = 0;
            }
        }
        // 执行刷新 : 行刷新
        for (int i = 0; i < matrix.length; i++) {
            if (matrix[i][0] != 0) {
                continue;
            }
            for (int j = 1; j < matrix[i].length; j++) {
                matrix[i][j] = 0;
            }
        }
        // 执行刷新 : 第0列刷新
        if (columnZeroFlag) {
            for (int i = 0; i < matrix.length; i++) {
                matrix[i][0] = 0;
            }
        }
        return matrix;
    }
}
